const Router = require('@koa/router')
const mongoose = require('mongoose')
const { getBody } = require('../utils/getBody')
const jwt = require('jsonwebtoken')
const config=require('../project.config')
const Auth = mongoose.model('Auth');
const InviteCode=mongoose.model('InviteCode')

const router = new Router({
    prefix: '/auth'
})
// /auth/register get
router.post('/register', async (ctx) => {
    console.log('ctx.request.body', ctx.request.body);
    const {
        username,
        password,
        inviteCode
    } = getBody(ctx)
   
    //表单校验
    if(username===''||password===''||inviteCode===''){
        ctx.body = {
            code: 0,
            msg: '输入错误',
            data: null
        }
        return
    }
    //db找邀请码
    const findCode=await InviteCode.findOne({
        code:inviteCode
    }).exec()
    if(!findCode){
        ctx.body = {
            code: 0,
            msg: '没有此邀请码',
            data: null
        }
        return
    }
    if(findCode.user!==''){
        ctx.body = {
            code: 0,
            msg: '该注册码已被使用过',
            data: null
        }
        return
    }
    //查数据库是否已有该用户
    const findUser = await Auth.findOne({ username }).exec()

    if (findUser) {
        ctx.body = {
            code: 0,
            msg: '已存在该用户',
            data: null
        }
        return
    }
    const auth = new Auth({
        username,
        password,
    });

    //更新数据到数据库
    const res = await auth.save()
    findCode.user=res._id //InviteCode的user与Auth的_id关联
    findCode.meta.updatedAt=new Date().getTime()
    await findCode.save()

    ctx.body = {
        code: 200,
        msg: '注册成功',
        data: res
    }
})
// /auth/login post
router.post('/login', async (ctx) => {
    //客户端传来的数据
    const {
        username,
        password
    } = getBody(ctx)
    //服务端数据校验
    if(username===''||password===''){
        ctx.body = {
            code: 0,
            msg: '用户名或密码错误',
            data: null
        }
        return
    }
    console.log('客户端返回', username, password);
    //查数据库是否已有该用户 不能传密码！
    const findUser = await Auth.findOne({ username }).exec()

    //接口返回给前端的数据
    const user = {
        username: findUser.username,
        character:findUser.character,
        _id: findUser._id
    }

    console.log('数据库返回', findUser);
    //登录用户名、密码都符合 success
    if (findUser.username === username && findUser.password == password) {
        ctx.body = {
            code: 200,
            msg: '登录成功',
            data: {
                auth: user, //返回前端剔除后的数据  auth:findUser这样会password也带过去 'wangmeng'
                token: jwt.sign(user, config.JWT_SECRET)
            }
        }
        return
    }
    //不存在 error
    if (!findUser) {
        ctx.body = {
            code: 0,
            msg: '用户名或密码错误',
            data: null
        }
        return
    }
    //其他情况error
    ctx.body = {
        code: 0,
        msg: '用户名或密码错误',
        data: null
    }
})
module.exports = router